package glory.xxd

import org.apache.activemq.ActiveMQConnectionFactory
import org.apache.commons.logging.LogFactory
import org.json.JSONObject

import javax.jms.*

/**
 * Created by Administrator on 2018-01-23.
 */
class ConsumerUtil {

    private final static logger = LogFactory.getLog(this)

    private static final String USERNAME = "admin";

    private static final String PASSWORD = "admin";

    //正式环境mq
//    private static final String BROKEURL = "tcp://10.10.10.44:61620"
    //测试环境
    private static final String BROKEURL = "tcp://192.168.33.240:61624"

    public static newMsgMap = [:]

    public static List<String> getQueueMsg(String msgId, String msgName) {

        List<String> list = new ArrayList<String>();
        Connection connection
        try {
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ConsumerUtil.USERNAME, ConsumerUtil.PASSWORD, ConsumerUtil.BROKEURL);
            connection = connectionFactory.createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(msgName);
            MessageConsumer messageConsumer = session.createConsumer(destination, "JMSCorrelationID='${msgId}'");
            //println messageConsumer.getMessageSelector();//延时20分钟
            TextMessage textMessage = (TextMessage) messageConsumer.receive(60 * 10 * 1000);
            if (textMessage) {
                list.add(textMessage.getText());
            }

            connection.close();
//            println "-------------${new Date()}接收Queue:${ConsumerUtil.BROKEURL}服务器链接正常!MSGID:${msgId}---------------"
            logger.info("-------------接收Queue:${ConsumerUtil.BROKEURL}服务器链接正常!MSGID:${msgId}---------------")
            logger.info(list[0])
        } catch (Exception e) {
//            println "-------------${new Date()}接收Queue:${ConsumerUtil.BROKEURL}服务器链接异常!MSGID:${msgId}---------------"
            logger.error("-------------接收Queue:${ConsumerUtil.BROKEURL}服务器链接异常!MSGID:${msgId}---------------")
            logger.error(e)
            connection.close();
        }

//        println list

        return list;
    }

    /**
     * 专门用于监听topic信息
     * @param msgName
     * @parma max 消息条数
     * @param newMsgMap
     */
    public static void getTopicMsg(String msgName, int max, Map<String, LinkedList> newMsgMap) {

        try {
            //创建一个ConnectionFactory对象连接MQ服务器
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ConsumerUtil.USERNAME, ConsumerUtil.PASSWORD, ConsumerUtil.BROKEURL);
            //创建一个连接对象
            Connection connection = connectionFactory.createConnection();
            //开启连接
            connection.start();
            //使用Connection对象创建一个Session对象
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //创建一个Destination对象。topic对象
            Topic topic = session.createTopic(msgName);
            //使用Session对象创建一个消费者对象。
            MessageConsumer consumer = session.createConsumer(topic);

            //接收消息
            consumer.setMessageListener(new MyListener() {

                @Override
                public void onMessage(Message message) {
                    try {
                        if (message) {
                            TextMessage textMessage = (TextMessage) message;
                            String xml = textMessage.getText()
                            String msgId = message.getJMSMessageID()

                            JSONObject json = Utils.getJsonObjectByXML(xml, "Request/.Body")
                            def eqpId = json.EQPID ?: ""
                            json.put("msgId", msgId)

                            if (eqpId) {
                                LinkedList list = newMsgMap?."${eqpId}"

                                if (list) {
                                    list.addLast(json)
                                    if (list.size() > max) {
                                        list.removeFirst()
                                    }

                                } else {
                                    list = LinkedList.newInstance()
                                    list.addFirst(json)
                                    newMsgMap.put(eqpId, list)
                                }
                            }

                            logger.info("msgId:${msgId}")
                            logger.info("报文:${xml}")
                        } else {
                            logger.debug("监听MQ运行中,暂无新消息...")
                        }

                    } catch (Exception e) {
                        logger.error("监听${msgName}：转换XML错误或网络异常!")
                        logger.error(e.getMessage())
                    }
                }
            });
        } catch (Exception e) {
            //println "监听${msgName}：异常!!"
            logger.error("连接MQ服务器：异常,可能网络中断")
            logger.error(e.getMessage())
        }
    }
}